<?php
namespace App\Http\Controllers;

use App\Exceptions\ValidateException;
use App\Model\Admin;
use App\Repository\Contracts\AdminInterface;
use App\Repository\Contracts\AdminJavaInterface;
use App\Support\Helper\CommonHelper;
use App\Support\Service\PrinterService;
use Illuminate\Http\Request;
use Auth;

/**
 * @Author:: HuangYin
 * @DateTime: 2017-01-10 14:47
 *
 * @Description:
 */
class AdminController extends Controller
{
    /**
     * @var Request
     */
    protected $request;

    /**
     * @var AdminInterface
     */
    protected $admin;

    /**
     * @var AdminJavaInterface
     */
    protected $adminJava;

    protected $uid;

    protected $storeId;

    /**
     * init
     *
     * AdminController constructor.
     * @param Request $request
     * @param AdminInterface $admin
     * @param AdminJavaInterface $adminJava
     */
    public function __construct(Request $request, AdminInterface $admin, AdminJavaInterface $adminJava)
    {
        $this->request = $request;

        $this->admin = $admin;

        $this->adminJava = $adminJava;

        $this->uid = CommonHelper::getToken(Auth::user())['uid'];

        $this->storeId = CommonHelper::getToken(Auth::user())['storeId'];
    }

    /**
     * @return \Illuminate\Http\JsonResponse
     */
    public function index()
    {
        $limit = $this->request->input('limit', 15);
        $page = $this->request->input('page', 1);
        $list = $this->admin->lists($limit, $page);

        return $this->success($list);
    }

    /**
     * @param $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function detail($id)
    {
        $detail = $this->admin->detail($id);

        return $this->success($detail);
    }

    /**
     * @return \Illuminate\Http\JsonResponse
     */
    public function created()
    {
        try {
            $data = $this->request->only(['phone', 'password', 'rePassword', 'real_name']);
            $data['role_id'] = $this->request->input('role_id')?:Admin::STORE_MANAGER;
            // 返回的店铺信息
            $data['store_id'] = $this->request->input('storeId')?:$this->storeId;
            $data['storeName'] = $this->request->input('storeName')?:null;
            $data['shopkeeper'] = $this->request->input('shopkeeper')?:null;
            $data['tel'] = $this->request->input('tel')?:null;
            $data['address'] = $this->request->input('address')?:null;
            $id = $this->admin->created($data);

            return $this->success($id);
        } catch (ValidateException $e) {

            return $this->validateError($e);
        }
    }

    /**
     * Update
     *
     * @param $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function updated($id)
    {
        try {
            $data = $this->request->only(['phone', 'password', 'rePassword', 'real_name']);
            $result = $this->admin->updated($id, $data);

            return $this->success($result);
        } catch (ValidateException $e) {

            return $this->validateError($e);
        }
    }

    /**
     * Update Password
     *
     * @param $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function updatePwd($id)
    {
        if ($id != $this->uid) {
            return $this->fail('没有操作权限~');
        }

        try {
            $password = $this->request->input('password');
            $newPassword = $this->request->input('newPassword');
            $result = $this->admin->updatePwd($this->uid, $password, $newPassword);

            return $this->success($result);
        } catch (ValidateException $e) {

            return $this->validateError($e);
        }
    }

    /**
     * Reset Password
     *
     * @param $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function resetPwd($id)
    {
        try {
            $result = $this->admin->resetPwd($id);

            return $this->success($result);
        } catch (ValidateException $e) {

            return $this->validateError($e);
        }
    }

    /**
     * Sign In
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function login()
    {

        try {
            $data = $this->request->only(['phone', 'password']);
            $userInfo = $this->admin->signIn($data);

            return $this->success($userInfo);
        } catch (ValidateException $e) {


            return $this->validateError($e);
        }
    }

    /**
     * @return \Illuminate\Http\JsonResponse
     */
    public function logout()
    {
        try {
            $result = $this->admin->logout($this->uid);

            return $this->success($result);
        } catch (ValidateException $e) {


            return $this->validateError($e);
        }
    }

    /**
     * 日志列表 [$uid == 0 ? '所有日志' : '单个用户日志']
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function operationList()
    {
        $limit = $this->request->input('limit', 15);
        $page = $this->request->input('page', 1);
        $uid = $this->request->input('uid', 0);
        $list = $this->admin->operationList($limit, $page, $uid);

        return $this->success($list);
    }

    /**
     * 搜索店铺
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function searchStore()
    {
        try {
            $keyword = $this->request->input('storeName');
            $data = $this->adminJava->searchStore($keyword);
            $result = [];
            if (!$data) return $this->success($result);
            foreach ($data['resultData'] as $val) {
                $result[] = ['storeName' => $val['stockPlaceName'], 'storeId' => $val['stockPlaceId']];
            }

            return $this->success($result);
        } catch (ValidateException $e) {

            return $this->validateError($e);
        }
    }

    /**
     * 匹配店铺
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function matchingStore()
    {
        try {
            $data = $this->request->only(['storeName', 'shopkeeper', 'phone']);
            $storeInfo = $this->adminJava->matchingStore($data);
            $result = [];
            if ($storeInfo['resultData']) {
                $result = [
                    'storeId' => $storeInfo['resultData']['stockPlaceId'],
                    'storeName' => $storeInfo['resultData']['stockPlaceName'],
                    'shopkeeper' => $storeInfo['resultData']['empBean']['empName'],
                    'tel' => $storeInfo['resultData']['empBean']['phoneNumber'],
                    'address' => $storeInfo['resultData']['stockPlaceAddress'],
                ];
            }

            return $this->success($result);
        } catch (ValidateException $e) {

            return $this->validateError($e);
        }
    }

    /**
     * 授权登录
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function authLogin()
    {
        try {
            $username = $this->request->input('username');
            $password = $this->request->input('password');
            $result = $this->adminJava->authLogin($username, $password);

            return $this->success($result['resultType'], $result['resultMsg']);
        } catch (ValidateException $e) {

            return $this->validateError($e);
        }
    }

    /**
     * @return \Illuminate\Http\JsonResponse
     */
    public function isAuth()
    {
        if (env('JAVA_USERNAME')) {

            return $this->success();
        } else {

            return $this->fail('你还未授权');
        }
    }

    /**
     * Net Status
     */
    public function netStatus()
    {
        $filePath = '../.env';
        $headers = get_headers(env('JAVA_RESOURCE'));
        if (strpos($headers[0], '200')) {
            $env = file_get_contents($filePath);
            $newEnv = str_replace('JAVA_NETWORK=0', 'JAVA_NETWORK=1', $env);
            file_put_contents($filePath, $newEnv);
        } else {
            $env = file_get_contents($filePath);
            $newEnv = str_replace('JAVA_NETWORK=1', 'JAVA_NETWORK=0', $env);
            file_put_contents($filePath, $newEnv);
        }
    }

    public function printers()
    {
        $bill = [
            ['name' => '测试商品00001', 'counts' => 3, 'price' => '21.9'],
            ['name' => '测试商品00002', 'counts' => 1, 'price' => '79.5'],
            ['name' => '测试商品00003', 'counts' => 2, 'price' => '45']
        ];
        $data = [
            'supermarket' => '重庆象米国际欧洲生活品质超市',
            'storeName' => '【紫荆广场店】',
            'address' => '重庆市江北区紫荆广场1楼',
            'tel' => '400-000-9011',
            'time' => date('Y年m月d日 H:i:s'),
            'slogan' => '感谢惠顾，欢迎再次光临！',
            'hotTitle' => '服务监督热线',
            'hotTel' => '400-000-9011',
            'refund' => '购物小票为退/换货',
            'voucher' => '开具发票等有效凭证',
            'keeping' => '请妥善保管',
        ];
        $printer = new PrinterService($data, $bill);
        //$printer->start();
    }
}